<?php
/**
 * Ruth Library
 * $Id$
 *
 * LICENSE
 *
 * Copyright (c) 2007, Chris Utz
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the Impact Lab nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY CHRIS UTZ ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL CHRIS UTZ BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * @category   Ruth
 * @package    Ruth_Ext
 * @author     Chris Utz <chris@chrisutz.com>
 * @copyright  2007 Chris Utz <chris@chrisutz.com>
 * @license    http://www.opensource.org/licenses/bsd-license.php    New BSD License
 * @version    $Revision$
 */

/**
 * @see Ruth_Channel
 */
require_once 'Ruth/Channel.php';

/**
 * @see Ruth_Message_Catalog
 */
require_once 'Ruth/Message/Catalog.php';

/**
 * Generates a response containing validation information to a submitted form
 * built using the ext.js toolkit. This class generates the response in JSON
 * format, the default for ext.js. Subclasses can overload the _generateResponse
 * method to write other formats.
 *
 * @category   Ruth
 * @package    Ruth_Ext
 * @subpackage Ruth_Ext_Form_Action
 * @author     Chris Utz <chris@chrisutz.com>
 * @copyright  2007 Chris Utz <chris@chrisutz.com>
 * @license    http://www.opensource.org/licenses/bsd-license.php    New BSD License
 * @version    $Revision$
 */
class Ruth_Ext_Form_Action_SubmitResponse
{
    /**
     * The channel filtering and validating the submit we are responding to.
     *
     * @var Ruth_Channel
     */
    protected $_channel;

    /**
     * The catalog to lookup validation error messages in.
     *
     * @var Ruth_Message_Catalog
     */
    protected $_catalog;

    /**
     * Whether or not a subclass should issue a success or failure response.
     *
     * @var boolean
     */
    protected $_success = false;

    /**
     * An array of error messages. The keys of the array are the names of the fields.
     *
     * @var array
     */
    protected $_errors  = array();

    /**
     * Instantiates a Ruth_Ext_Form_Action_SubmitResponse_Abstract object.
     *
     * @param Ruth_Channel $channel
     * @param Ruth_Message_Catalog $catalog
     * @return void
     */
    public function __construct(Ruth_Channel $channel, Ruth_Message_Catalog $catalog)
    {
        $this->_channel = $channel;
        $this->_catalog = $catalog;
    }

    /**
     * Returns a submit response in a particular format to a form constructed 
     * using ext.js. The format used is contingent upon the subclass of 
     *
     * @param array Optional extra data to add to the response.
     * @return string The response string.
     */
    public function getResponseString(array $extraData = array())
    {
        $this->_extraData = $extraData;

        if ($this->_channel->isValid()) {
            $this->_success = true;
        } else {
            $this->_success = false;

            foreach ($this->_channel as $field) {
                if (!$field->isValid) {
                    $failures = $field->getFailures();

                    try {
                        $msg = $this->_catalog->getOnFailure($field, $failures[0]);
                    } catch (Ruth_Message_Exception $e) {
                        try {
                            $msg = $this->_catalog->getOnFailure($field, 'Valid');
                        } catch (Ruth_Message_Exception $e) {
                            continue;
                        }
                    }

                    $this->_errors[$field->getName()] = (string) $msg;
                }
            }
        }

        return $this->_generateResponse();
    }

    /**
     * Generates the response string in JSON format. This method can be
     * overridden by subclasses to generate responses in other formats.
     *
     * @return string Response encoded in JSON format.
     */
    protected function _generateResponse()
    {
        return json_encode(array_merge(
            $this->_extraData,
            array(
                'success' => $this->_success,
                'errors'  => $this->_errors
            )
        ));
    }
}
 
// vim: sw=4:ts=4:sts=4:et
